package com.example.repository;

import com.example.common.ReflectionUtils;
import org.elasticsearch.action.update.UpdateResponse;
import org.springframework.data.domain.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.stereotype.Repository;

/**
 * Created by Chenjie on 2017/7/12.
 */
@Repository
public class BaseESDAO<T> {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public String save(T t) {
        IndexQuery indexQuery = new IndexQuery();
        indexQuery.setObject(t);
        return elasticsearchTemplate.index(indexQuery);
    }

    public boolean remove(CriteriaQuery query) {
        elasticsearchTemplate.delete(query, this.getEntityClass());
        return true;
    }

    public String update(UpdateQuery query) {
        UpdateResponse update = elasticsearchTemplate.update(query);
        return update.getId();
    }

    public T queryForObject(CriteriaQuery query) {
        return elasticsearchTemplate.queryForObject(query, this.getEntityClass());
    }

    public Page<T> queryForPage(CriteriaQuery query) {
        return elasticsearchTemplate.queryForPage(query, this.getEntityClass());
    }

    public Page<T> queryForPage(SearchQuery query) {
        return elasticsearchTemplate.queryForPage(query, this.getEntityClass());
    }

    /**
     * 获取需要操作的实体类class
     *
     * @return
     */
    private Class<T> getEntityClass() {
        return ReflectionUtils.getSuperClassGenricType(getClass());
    }
}
